<template>
  <el-card>
    <el-button type="primary" @click="showAddDialog">新增用户</el-button>
    <br />    <br />
    <el-table :data="users" style="width: 100%">
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="role" label="角色">
      <template #default="{ row }">
        <span v-if="row.role === 0">管理员</span>
        <span v-else>普通用户</span>
      </template> 
      
      </el-table-column>
      <el-table-column prop="password" label="密码"></el-table-column>

      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="danger" @click="deleteUser(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="新增用户">
      <el-form :model="form" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-radio-group v-model="form.role">
            <el-radio :label="0">管理员</el-radio>
            <el-radio :label="1">普通用户</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive } from "vue";
import http from "../utils/http";

const users = ref([]);
const form = reactive({
  name: "",
  username: "",
  password: "",
  role: 1,
});
const dialogVisible = ref(false);

// 获取用户列表
http
  .get("/user/list")
  .then((response) => {
    users.value = response.data.data;
  })
  .catch((error) => {
    console.error(error);
  });

// 显示新增用户对话框
const showAddDialog = () => {
  form.name = "";
  form.username = "";
  form.password = "";
  form.role = 1;
  dialogVisible.value = true;
};

// 新增用户
const addUser = () => {
  if (!form.name || !form.username || !form.password) {
    return;
  }
  http
    .post("/user/add", form)
    .then((response) => {
      users.value.push(response.data.data);
      dialogVisible.value = false;
    })
    .catch((error) => {
      console.error(error);
    });
};

// 显示编辑用户对话框
const showEditDialog = (user) => {
  form.name = user.name;
  form.username = user.username;
  form.password = user.password;
  form.role = user.role;
  dialogVisible.value = true;
};

// 删除用户
const deleteUser = (id) => {
  http
    .post("/user/delete", { id })
    .then(() => {
      users.value = users.value.filter((user) => user.id !== id);
    })
    .catch((error) => {
      console.error(error);
    });
};
</script>
